package com.sdlogan.pbudget;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * The main class that will launch when the application is launched
 * @author Sean
 *
 */
public class Main extends Activity {
    /** Called when the activity is first created. */
	MoneyTable mt;
	Intent myIntent;
	List<dbPackage> source;
	double monthincome;
	double monthexpense;
	double monthoverall;
	double yearincome;
	double yearexpense;
	double yearoverall;
	dbPackage currentItem;
	Iterator it;
	String year;
	String month;
	TextView income;
	TextView expense;
	TextView overall;
	TextView yincome;
	TextView yexpense;
	TextView yoverall;
	
	/**
	 * 
	 * Initialize all the variables, set the xml layout
	 */
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Calendar cal = Calendar.getInstance();
		year = Integer.toString(cal.get(Calendar.YEAR),10);
		Date date = new Date();
		month = new SimpleDateFormat("MMMM").format(date);
        mt = new MoneyTable(this);
        mt.open();
        source = mt.getAllRows();
        mt.close();
        monthincome = 0.0;
        monthexpense = 0.0;
        monthoverall = 0.0;
        yearincome = 0.0;
        yearexpense = 0.0;
        yearoverall = 0.0;
        currentItem = null;
        //Toast.makeText(this, "Number of Items: " + source.size() + ".", Toast.LENGTH_LONG).show();
        
        it = source.iterator();
        
        final Spinner monthspin = (Spinner) findViewById(R.id.monthspinner);
        ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
                this, R.array.month_array, android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        monthspin.setAdapter(adapter1);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.year_array, android.R.layout.simple_spinner_item);
        final Spinner yearspin = (Spinner) findViewById(R.id.yearspinner);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        yearspin.setAdapter(adapter2);
        income = (TextView) findViewById(R.id.monthincome);
        income.setTextColor(Color.GREEN);
        expense = (TextView) findViewById(R.id.monthexpense);
        expense.setTextColor(Color.RED);
        overall = (TextView) findViewById(R.id.monthoverall);
        yincome = (TextView) findViewById(R.id.yearincome);
        yincome.setTextColor(Color.GREEN);
        yexpense = (TextView) findViewById(R.id.yearexpense);
        yexpense.setTextColor(Color.RED);
        yoverall = (TextView) findViewById(R.id.yearoverall);
        
        updateValues(month,year);
        Button filter = (Button) findViewById(R.id.mainfilter);
        filter.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				String selectedMonth = (String) monthspin.getSelectedItem();
				String selectedYear = (String) yearspin.getSelectedItem();
				updateValues(selectedMonth,selectedYear);
				
			}
		});
    }
        
    	
    /**
     * Initialize the Options Menus
     * 
     */
    	public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.mainmenu, menu);
            return true;
    }
    	
    	/**
    	 * This method updates the variables and sets the textviews located on the page
    	 * @param m.  The month selected in the spinner dial
    	 * @param y	  The year selected in the spinner dial
    	 */
    	
    	public void updateValues(String m, String y) {
    		it = source.iterator();
    		monthincome = 0.0;
    		monthexpense = 0.0;
    		monthoverall = 0.0;
            yearincome = 0.0;
            yearexpense = 0.0;
            yearoverall = 0.0;
    		Double mvalue = 0.0;
    		Double yvalue = 0.0;
    		while (it.hasNext()) {
        		currentItem = (dbPackage) it.next();
        		mvalue = 0.0;
        		yvalue = 0.0;
        		mvalue = getMonthValue(currentItem,m,y);
        		yvalue = getYearlyValue(currentItem,m,y);
        		if (currentItem.type.equals("Income")) {
        			monthincome += mvalue;
        			yearincome += yvalue;
        		}
        		else {
        			monthexpense += mvalue;
        			yearexpense += yvalue;
        		}
        		
        }
    	DecimalFormat twoDForm = new DecimalFormat("#.##");
        income.setText("Monthly Income = " + twoDForm.format(monthincome));
        expense.setText("Monthly Expenses = " + twoDForm.format(monthexpense));
        monthoverall = monthincome - monthexpense;
        yearoverall = yearincome - yearexpense;
        if (monthoverall < 0) {
        	overall.setTextColor(Color.RED);
        	overall.setText("Monthly Overall : " + twoDForm.format(monthoverall));
        	Toast.makeText(getBaseContext(), "Warning, Negative Account", Toast.LENGTH_LONG).show();
        	}
        else if (monthoverall > 0){
        	overall.setTextColor(Color.GREEN);
        	overall.setText("Monthly Overall : " + twoDForm.format(monthoverall));
        	}
        else {
        	overall.setTextColor(Color.GRAY);
        	overall.setText("Monthly Overall : " + twoDForm.format(monthoverall));
        	}
        yincome.setText("Yearly Income = " + twoDForm.format(yearincome));
        yexpense.setText("Yearly Expenses = " + twoDForm.format(yearexpense));
        if (yearoverall < 0) {
        	yoverall.setTextColor(Color.RED);
        	yoverall.setText("Yearly Overall :" + twoDForm.format(yearoverall));
        	}
        else if (yearoverall == 0) {
        	yoverall.setTextColor(Color.GRAY);
        	yoverall.setText("Yearly Overall : " + twoDForm.format(yearoverall));
        	}
        else {
        	yoverall.setTextColor(Color.GREEN);
        	yoverall.setText("Yearly Overall : " + twoDForm.format(yearoverall));
        	}
    	}
    	
    	/**
    	 * Gets the values for each month
    	 * @param dp : The current Package
    	 * @param m  : The month selected
    	 * @param y  : The year selected
    	 * @return   : Returns the value to be used
    	 */
    	public double getMonthValue(dbPackage dp,String m,String y) {
			double value = 0.0;
    		if (dp.occurence.equals("One-Time")) {
    			if (dp.month.equals(m) && dp.year.equals(y)) {
    				return dp.value;
    			}
    			else {
    				return 0.0;
    			}
    		}
    		else {
    			if (dp.occurence.equals("Weekly")) {
    				value = dp.monthlyvalue;
    			}
    			else if (dp.occurence.equals("Bi-Weekly")) {
    				value = dp.monthlyvalue;
    			}
    			else if (dp.occurence.equals("Monthly")) {
    				value = dp.monthlyvalue;
    			}
    			else if (dp.occurence.equals("Quarterly")) {
    				if ((getMonth(dp.month)+ 1) % 3 == 0) {
    					value = dp.monthlyvalue;
    				}
    				else {
    					value = 0.0;
    				}
    			}
    			else if (dp.occurence.equals("Bi-Yearly")) {
    				if ((getMonth(dp.month)+1) % 6 == 0) {
    					value = dp.value;
    				}
    				else {
    					value = 0.0;
    				}
    			}
    			else {
    				if ((getMonth(dp.month)+1) % 12 == 1) {
    					value = dp.value;
    				}
    				else {
    					value = 0.0;
    				}
    			}
    		}
    		if (getMonth(m) <= getMonth(month) && Integer.parseInt(y) >= Integer.parseInt(year)) {
    			if (getMonth(m) >= getMonth(dp.month) && Integer.parseInt(y) >= Integer.parseInt(dp.year)) {
        			return value;
    			}
    			else {
    				return 0.0;
    			}
    		}
    		else {
    			return 0.0;
    		}
    	}
    	
    	/**
    	 * Returns the yearly value to be used
    	 * @param dp  : The current package
    	 * @param month : The month selected
    	 * @param y     : The year selected
    	 * @return      : Return the value to be used
    	 */
    	
    	public double getYearlyValue(dbPackage dp,String month,String y) {
    		if (Integer.parseInt(y) >= Integer.parseInt(dp.year)) {
    			return dp.yearlyvalue;
    		}
    		else {
    			return 0.0;
    		}
    	}
    	
    	/**
    	 * Returns a numerical representation of the month name
    	 * @param name : The string value of the month
    	 * @return     : The int value of the month
    	 */
    	
    	public int getMonth(String name) {
			if (name.equals("January")) {
				return 0;
			}
			else if (name.equals("February")) {
				return 1;
			}
			else if (name.equals("March")) {
				return 2;
			}
			else if (name.equals("April")) {
				return 3;
			}
			else if (name.equals("May")) {
				return 4;
			}
			else if (name.equals("June")) {
				return 5;
			}
			else if (name.equals("July")) {
				return 6;
			}
			else if (name.equals("August")) {
				return 7;
			}
			else if (name.equals("September")){
				return 8;
			}
			else if (name.equals("October")) {
				return 9;
			}
			else if (name.equals("November")) {
				return 10;
			}
			else {
				return 11;
			}
		}
    	
    	/**
    	 * Handles the on on click events from the menu
    	 * 
    	 */
    	
    	public boolean onOptionsItemSelected(MenuItem item) {
    		String type = null;
			switch (item.getItemId()) {
			case R.id.home:
				Log.i("Sean","Pressed Home");
				myIntent = new Intent(Main.this, Main.class);
				startActivityForResult(myIntent,0);
				return true;
			case R.id.graphs:
				return true;
			case R.id.incomechart:
				Log.i("Sean","income Graph");
				myIntent = new Intent(Main.this,Graphs.class);
				myIntent.putExtra("type","Income");
				startActivityForResult(myIntent,0);
				return true;
			case R.id.expensechart:
				Log.i("Sean","expense graph");
				myIntent = new Intent(Main.this,Graphs.class);
				myIntent.putExtra("type","Expense");
				startActivityForResult(myIntent,0);
				return true;
			case R.id.incomes:
				Log.i("Sean","Pressed Result");
				myIntent = new Intent(Main.this, Incomes.class);
				startActivityForResult(myIntent,0);
				return true;
			case R.id.expenses:
				Log.i("Sean","Pressed Expense");
				myIntent = new Intent(Main.this,Expenses.class);
				startActivityForResult(myIntent,0);
				return true;
			case R.id.export:
				Log.i("Sean","Pressed Export");
				myIntent = new Intent(Main.this, Export.class);
				startActivityForResult(myIntent,0);
				return true;
			case R.id.newvalue:
				Log.i("Sean","Pressed New");
				return true;
			case R.id.incomenew:
				Log.i("Sean","Pressed Income");
				myIntent = new Intent(Main.this,SubmitForm.class);
				myIntent.putExtra("type","Income");
				startActivityForResult(myIntent,0);
				return true;
			case R.id.expensenew:
				Log.i("Sean","Pressed Expense");
				myIntent = new Intent(Main.this,SubmitForm.class);
				myIntent.putExtra("type","Expense");
				startActivityForResult(myIntent,0);
				return true;
			default: 
				return false;
			}
			
    	}
}